using System.Text.Json;
using StackExchange.Redis;

namespace ORS.OrderRobot.Queue
{
    /// <summary>
    /// Redis消息队列实现
    /// </summary>
    public class RedisMessageQueue<T> : IMessageQueue<T>
    {
        private readonly IConnectionMultiplexer _redis;
        private readonly IDatabase _db;
        private readonly string _queueKey;
        private readonly RedisOptions _options;

        public RedisMessageQueue(IConnectionMultiplexer redis, RedisOptions options, string queueName)
        {
            _redis = redis ?? throw new ArgumentNullException(nameof(redis));
            _options = options ?? throw new ArgumentNullException(nameof(options));
            _db = redis.GetDatabase(_options.DefaultDatabase);
            _queueKey = $"queue:{queueName}";
        }

        public async Task EnqueueAsync(T item, CancellationToken cancellationToken = default)
        {
            var jsonValue = JsonSerializer.Serialize(item);
            await _db.ListRightPushAsync(_queueKey, jsonValue);
        }

        public async Task<T> DequeueAsync(CancellationToken cancellationToken = default)
        {
            var value = await _db.ListLeftPopAsync(_queueKey);
            if (!value.HasValue)
            {
                return default;
            }

            return JsonSerializer.Deserialize<T>(value);
        }

        public int Count => (int)_db.ListLength(_queueKey);
    }
} 